<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>聊天室</title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }
      .app {
        width: 500px;
        margin: 20px auto;
      }
      .container {
        width: 100%;
        height: 400px;
        border: 1px solid #000;
      }
    </style>
  </head>
  <body>
    <div class="app">
      <div class="container"></div>
      <textarea cols="30" rows="10" class="text"></textarea>
      <button class="btn">发送消息</button>
    </div>
    <script>
      const socket = new WebSocket("ws://192.168.21.126:3000");

      const containerEl = document.querySelector(".container");
      const textEl = document.querySelector(".text");
      const btnEl = document.querySelector(".btn");

      // 发送消息
      btnEl.onclick = function () {
        const text = textEl.value.trim();
        if (!text) return;
        socket.send(text);
        textEl.value = "";
        containerEl.innerHTML += `<div>${text}</div>`;
      };

      // 接受消息
      socket.onmessage = function (e) {
        const text = e.data;
        containerEl.innerHTML += `<div>${text}</div>`;
      };
    </script>
  </body>
</html>
